<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true" label-width="100px">
        <el-form-item label="订单编号">
          <el-input
            v-model="searchParam.orderNo"
            placeholder="请输入订单编号"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <div v-if="isExpanded">
          <el-form-item label="送货单号">
            <el-input
              v-model="searchParam.asnCode"
              placeholder="请输入送货单号"
              clearable
              @keyup.enter="search"
            />
          </el-form-item>

          <el-form-item label="供应商编号">
            <el-input
              v-model="searchParam.partnerCode"
              placeholder="请输入供应商编号"
              clearable
              @keyup.enter="search"
            />
          </el-form-item>
          <el-form-item label="到货日期">
            <el-date-picker
              v-model="searchParam.arriveDateSearch"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD HH:mm:ss"
              @change="getarriveDate"
            />
          </el-form-item>
          <el-form-item label="运单号">
            <el-input
              v-model="searchParam.trackingNumber"
              placeholder="请输入运单号"
              clearable
              @keyup.enter="search"
            />
          </el-form-item>

          <el-form-item label="承运人">
            <el-input
              v-model="searchParam.carrier"
              placeholder="请输入承运人"
              clearable
              @keyup.enter="search"
            />
          </el-form-item>
          <el-form-item label="发货状态">
            <el-select
              v-model="searchParam.shipmentStatus"
              placeholder="请选择发货状态"
              clearable
            >
              <el-option
                v-for="item in useDictionary('ShipmentStatus')"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="创建时间">
            <el-date-picker
              v-model="searchParam.createTimeSearch"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD HH:mm:ss"
              @change="getcreateTime"
            />
          </el-form-item>

          <el-form-item label="修改时间">
            <el-date-picker
              v-model="searchParam.lastUpdateTimeSearch"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD HH:mm:ss"
              @change="getlastUpdateTime"
            />
          </el-form-item>
        </div>
        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="reset"><i-ep-refresh />重置</el-button>
          <el-button type="primary" @click="toggleSearchArea" link>
            {{ isExpanded ? "收起" : "展开" }}
            <el-icon v-if="isExpanded" class="el-icon--right">
              <i-ep-arrowUp color="#409EFC" />
            </el-icon>
            <el-icon v-else class="el-icon--right">
              <i-ep-arrowDown color="#409EFC" />
            </el-icon>
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" plain @click="openDialog()"
          ><i-ep-plus />新增</el-button
        >
      </template>
      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          label="QAD订单编号"
          prop="orderNo"
          min-width="150"
          show-overflow-tooltip
        />
        <el-table-column
          label="发货状态"
          prop="shipmentStatus"
          min-width="100"
          align="center"
        >
          <template #default="scope">
            {{ useDictionary("ShipmentStatus", scope.row.shipmentStatus) }}
          </template>
        </el-table-column>

        <el-table-column
          label="公司编号"
          prop="organizationCode"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="公司名称"
          prop="organizationName"
          min-width="220"
          show-overflow-tooltip
        />

        <el-table-column
          label="工厂"
          prop="plantCode"
          min-width="100"
          show-overflow-tooltip
        />

        <el-table-column
          label="送货单号"
          prop="asnCode"
          min-width="135"
          show-overflow-tooltip
        />

        <el-table-column
          label="供应商编号"
          prop="partnerCode"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="供应商名称"
          prop="partnerName"
          min-width="240"
          show-overflow-tooltip
        />

        <el-table-column
          label="到货日期"
          prop="arriveDate"
          min-width="120"
          show-overflow-tooltip
          :formatter="formatDate"
          align="center"
        />
        <el-table-column
          label="运单号"
          prop="trackingNumber"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="承运人"
          prop="carrier"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="备注"
          prop="remarks"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="创建时间"
          prop="createTime"
          min-width="180"
          show-overflow-tooltip
          align="center"
        />

        <el-table-column
          label="创建人"
          prop="createdUserName"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="修改时间"
          prop="lastUpdateTime"
          min-width="180"
          show-overflow-tooltip
          align="center"
        />

        <el-table-column
          label="修改人"
          prop="lastUpdatedUserName"
          min-width="100"
          show-overflow-tooltip
        />

        <el-table-column fixed="right" label="操作" width="150" align="center">
          <template #default="scope">
            <el-dropdown size="small">
              <el-button type="primary" size="small" style="width: 75px">
                更多菜单
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="openDialogdetail(scope.row)"
                    >查看</el-dropdown-item
                  >
                  <el-dropdown-item
                    :disabled="scope.row.shipmentStatus === '4'"
                    @click="openDialog(scope.row)"
                    >编辑</el-dropdown-item
                  >
                  <el-dropdown-item
                    :disabled="scope.row.shipmentStatus === '4'"
                    @click="openDialogreveive(scope.row)"
                    >收货</el-dropdown-item
                  >

                  <el-dropdown-item
                    :disabled="scope.row.shipmentStatus === '4'"
                    @click="handleTableDelete(scope.row.id)"
                    >删除</el-dropdown-item
                  >
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <srmasnpart-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
    <srmasnpart-editreceive
      :visible="addDialogreceive.visible"
      :title="addDialogreceive.title"
      :data="addDialogreceive.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialogreceive.readvisible"
      @change-visible="changeVisiblereceive"
    />
    <iframe
      v-if="showWebView"
      :src="webviewSrc"
      :update-title="false"
      style="width: 0; height: 0"
    ></iframe>
    <div id="printBox" v-if="isPrint" style="opacity: 0">
      <div
        style="margin-bottom: 20px"
        v-for="item in printData"
        :key="item?.id"
      >
        <div
          :id="`printId_${item?.id || ''}`"
          style="width: 394px; height: 394px"
        >
          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
          <!-- <canvas :id="`barcode_${item?.id || ''}`"></canvas> -->
          <div
            style="
              font-size: 12px;
              font-weight: 600;
              word-break: break-all;
              width: 390px;
            "
          >
            <span style="font-size: 18px; font-weight: 100; margin-right: 20px"
              ><text
                style="font-size: 20px; font-weight: 600; margin-right: 20px"
                >{{ item?.unitBarcode || "" }}</text
              ></span
            >
          </div>
          <div style="font-size: 14px; margin-bottom: -10px; width: 390px">
            <span
              style="
                font-size: 18px;
                font-weight: 100;
                margin-right: 20px;
                font-weight: 600;
              "
              >存货编码：&nbsp;<text
                style="font-size: 20px; font-weight: 600; margin-right: 20px"
                >{{ item?.materialCode || "" }}</text
              ></span
            >
            <span
              style="
                font-size: 18px;
                font-weight: 100;
                margin-right: 20px;
                font-weight: 600;
              "
              >材质：&nbsp;<text style="font-size: 20px; font-weight: 600">{{
                item?.materialQuality || ""
              }}</text></span
            >
          </div>
          <div style="font-size: 14px; margin-bottom: -10px; width: 390px">
            <br />
            <span
              style="
                font-size: 18px;
                font-weight: 100;
                margin-right: 20px;
                font-weight: 600;
              "
              >规格型号：&nbsp;<text
                style="font-size: 20px; font-weight: 600"
                >{{ item?.materialSpecification || "" }}</text
              ></span
            >
          </div>
          <div style="font-size: 14px; margin-bottom: -10px; width: 390px">
            <br />
            <span
              style="
                font-size: 18px;
                font-weight: 100;
                margin-right: 20px;
                font-weight: 600;
              "
              >图号：&nbsp;<text style="font-size: 20px; font-weight: 600">{{
                item?.figureNumber || ""
              }}</text></span
            >
          </div>
          <div style="font-size: 14px; margin-bottom: 0px; width: 390px">
            <br /><span
              style="
                font-size: 18px;
                font-weight: 100;
                margin-right: 10px;
                font-weight: 600;
              "
              >生产批次：<text
                style="font-size: 20px; font-weight: 600; margin-right: 10px"
                >{{ item?.supplyBatch || "" }}</text
              ></span
            >
            <span
              style="
                font-size: 18px;
                font-weight: 100;
                margin-right: 20px;
                font-weight: 600;
              "
              >数量：&nbsp;<text style="font-size: 20px; font-weight: 600"
                >{{ item?.quantity || "" }} {{ item?.unitName || "" }}</text
              >
            </span>
          </div>
          <div style="height: 5px"></div>
          <div style="font-size: 12px; width: 390px; margin-bottom: 1px">
            <span
              style="
                font-size: 12px;
                font-weight: 100;
                margin-right: 20px;
                font-weight: 600;
              "
              >打印时间：&nbsp;<text>{{ item?.printTime || "" }}</text></span
            >
            <span
              style="
                font-size: 12px;
                font-weight: 100;
                margin-right: 20px;
                font-weight: 600;
              "
              >打印人：&nbsp;<text
                >{{ item?.printUserName || "" }}&nbsp;</text
              ></span
            >
          </div>
          <div style="height: 5px"></div>
          <div style="font-size: 14px; width: 400px; display: flex">
            <span
              style="
                flex: 1;
                font-weight: 100;
                font-size: 14px;
                margin-right: 20px;
                font-weight: 600;
              "
              >操作者1：&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span
            >
            <span
              style="
                flex: 1;
                font-weight: 100;
                font-size: 14px;
                margin-right: 20px;
                font-weight: 600;
              "
              >操作者2：&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span
            >
            <span
              style="
                flex: 1;
                font-weight: 100;
                font-size: 14px;
                margin-right: 20px;
                font-weight: 600;
              "
              >检&nbsp;查：&nbsp;&nbsp;&nbsp;&nbsp;</span
            >
          </div>
          <div
            style="
              font-size: 17px;
              margin-bottom: 0px;
              width: 300px;
              font-weight: 600;
            "
          ></div>
        </div>
      </div>
      <div style="margin-top: 500px; text-align: center">
        <div style="display: flex; justify-content: center; gap: 10px">
          <el-button size="small" @click="getPrintData()">打印</el-button>
          <el-button size="small" @click="isPrint = false">返回</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useTable, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";
import { getLodop } from "@/utils/LocalLodopFuncs";
import { RootObject } from "@/views/demo/iframePrintUnit/index";

defineOptions({
  name: "SRMSRMASNPART",
  inheritAttrs: false,
});

// 请求参数
const requestApi = "/srm/srmasnpart/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  orderNo: "",
  organizationId: "",
  organizationCode: "",
  organizationName: "",
  plantId: "",
  plantCode: "",
  plantName: "",
  asnCode: "",
  partnerId: "",
  partnerCode: "",
  partnerName: "",
  asnDateSearch: [],
  asnDateStart: "",
  asnDateEnd: "",
  arriveDateSearch: [],
  arriveDateStart: "",
  arriveDateEnd: "",
  modeTransport: "",
  trackingNumber: "",
  storageLocationId: "",
  storageLocationCode: "",
  storageLocationName: "",
  carrier: "",
  shippingContactPerson: "",
  shippingContactPhone: "",
  plateNumber: "",
  shipmentStatus: "",
  remarks: "",
  createTimeSearch: [],
  createTimeStart: "",
  createTimeEnd: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTimeSearch: [],
  lastUpdateTimeStart: "",
  lastUpdateTimeEnd: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  deleted: "",
};

const deleteParam = {
  api: "/srm/srmasnpart/delete",
  data: {},
};
// 触发打印
const showWebView = ref(false);
const webviewSrc = ref("");
// 数据请求错误后处理
function requestError() {}
const isExpanded = ref(false);
const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行
const open = (row) => {
  ElMessageBox.confirm(`请确认是否打印？`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    beforeClose: (action, instance, done) => {
      if (action === "confirm") {
        // 开启按钮加载
        instance.confirmButtonLoading = true;
        // 调用打印页面
        // 跳转到指定页面
        //insertOperateLog(row.id);
        //window.location.href = `${IFRAME_URL}iframePrintSrmDeliveryUnit?id=${row.id}`;
        isPrint.value = true;
        printId.value = row.id;
        getPrintData();
        done();
      } else {
        done();
      }
    },
  }).catch(() => {});
};
// 获取打印数据
async function getPrintData() {
  const { data } = await request({
    url: `/srm/srmasnpackingdetail/getUnitList/${printId.value}`,
    method: "get",
    data: {},
  }).finally(() => {});
  //printData.value = [data, data, data]; //多张打印
  printData.value = data; //单张打印

  nextTick(() => {
    printData.value?.map(async (e) => {
      const qrCodeId = `barcode_${e?.id || ""}`;
      const qrCodeElement = document.getElementById(qrCodeId);

      if (qrCodeElement) {
        try {
          await QRCode.toCanvas(qrCodeElement, e.unitBarcode || "", {
            width: 100, // 可以根据需要调整二维码的大小
            margin: 1, // 可以根据需要调整二维码的边距
          });
        } catch (err) {
          console.error("Error generating QR code:", err);
        }
      }
    });
  });
  setTimeout(() => {
    let LODOP = getLodop();
    LODOP.PRINT_INIT(`包装打印-${printId.value}`);
    // LODOP.SET_LICENSES(
    //   defaultSettings.printCompany,
    //   defaultSettings.printLicenses,
    //   "",
    //   ""
    // );
    printData.value?.map((e) => {
      printFun(e, LODOP);
    });
    //LODOP.SET_PRINTER_INDEX("ZDesigner ZT231-203dpi ZPL");
    //LODOP.PRINT(); // 打印
    console.log(LODOP.Printers.list);
    isPrint.value = false;
    LODOP.PREVIEW(); // 预览
    window.parent.postMessage("打印中，请稍后...", "*");
    insertOperateLog(printId.value);
  }, 1000);
}
const isPrint = ref(false);
let printId = ref("");
// 打印数据，数组形式
const printData = ref<RootObject[]>([]);
function printFun(pitem: RootObject, LODOP: any) {
  LODOP.SET_PRINT_PAGESIZE(1, "100mm", "100mm", ""); // 设置纸张类型（方向、宽度、高度、纸张类型名称）
  //LODOP.ADD_PRINT_RECT(0, 5, 310, 220, 0, 1); //边框设置：上、左、宽、高、线条：0实线 1虚线
  //LODOP.SET_PRINT_STYLE("FontSize", 7.5);
  //LODOP.SET_PRINT_STYLE("FontName", "cursive"); // 需要服务端机器安装同样字体，才能生效
  LODOP.ADD_PRINT_HTM(
    "40mm",
    "10mm",
    "100mm",
    "100mm",
    document.getElementById(`printId_${pitem?.id || ""}`)?.innerHTML
  );
  LODOP.ADD_PRINT_BARCODE(
    "5mm",
    "30mm",
    "40mm",
    "40mm",
    "QRCode",
    pitem?.unitBarcode || ""
  );
  LODOP.NEWPAGE(); //另起一页
}

//开始打印
async function insertOperateLog(id: any) {
  operateLog.value.info = id;
  await request({
    method: "POST",
    url: "/system/sysOperateLog/insert",
    data: operateLog.value,
  });
}
//打印日志信息
const operateLog = ref({
  logLevel: "INFO",
  applicationName: "jcfk-srm",
  modular: "收货单包装批量打印开始",
  businessType: "打印",
  info: "",
});
// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);
onMounted(() => {
  getTableList();
});

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});
const addDialogreceive = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/srm/srmasnpart/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}
// 查询详情
async function getInforeceive(id: string) {
  request({
    url: `/srm/srmasnpart/getInfo/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialogreceive.data = data.data;
      addDialogreceive.visible = true;
      console.log("1", addDialogreceive.data);
    })
    .catch((res) => {
      console.log(res);
    });
}
/** 打开ASN单表单弹窗 */
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "修改外购件收货单";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增外购件收货单";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}
function openDialogreveive(roleObj?: Object) {
  if (roleObj) {
    addDialogreceive.title = "收货";
    getInforeceive(roleObj.asnCode);
  }
  addDialogreceive.readvisible = false;
}

/** 打开ASN单表单(平面级)弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "外购件收货单详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}
function toggleSearchArea() {
  isExpanded.value = !isExpanded.value;
}
function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}
function changeVisiblereceive(value: boolean) {
  addDialogreceive.visible = value;
  if (!value) {
    addDialogreceive.data = {};
  }
}
function getasnDate(data: any) {
  if (data) {
    searchParam.value.asnDateStart = data[0];
    searchParam.value.asnDateEnd = data[1];
  } else {
    searchParam.value.asnDateStart = "";
    searchParam.value.asnDateEnd = "";
  }
}
function getarriveDate(data: any) {
  if (data) {
    searchParam.value.arriveDateStart = data[0];
    searchParam.value.arriveDateEnd = data[1];
  } else {
    searchParam.value.arriveDateStart = "";
    searchParam.value.arriveDateEnd = "";
  }
}
function getcreateTime(data: any) {
  if (data) {
    searchParam.value.createTimeStart = data[0];
    searchParam.value.createTimeEnd = data[1];
  } else {
    searchParam.value.createTimeStart = "";
    searchParam.value.createTimeEnd = "";
  }
}
function getlastUpdateTime(data: any) {
  if (data) {
    searchParam.value.lastUpdateTimeStart = data[0];
    searchParam.value.lastUpdateTimeEnd = data[1];
  } else {
    searchParam.value.lastUpdateTimeStart = "";
    searchParam.value.lastUpdateTimeEnd = "";
  }
}
function formatDate(row, column) {
  const date = row[column.property];
  if (!date) return "";
  return date.split(" ")[0]; // 返回日期的年月日部分，而隐藏时间部分
}
</script>
